package com.cyp.livelog.utils;


import com.mysql.jdbc.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author 日月星辰
 * @date 2020/12/15 18:36
 * @description
 */
public class DbUtils {

  //表示数据库的用户名
  private final String USERNAME = "root";
  //表示数据库的密码
  private final String PASSWORD = "123456";
  //数据库的驱动信息
  private final String DRIVER = "com.mysql.jdbc.Driver";
  //访问数据库的地址
  private final String URL = "jdbc:mysql://localhost:3306/live?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=Asia/Shanghai";
  private static Connection conn = null;

  //构造函数
  public DbUtils() {
    try {
      Class.forName(DRIVER);
      System.out.println("注册驱动成功");
      conn = (Connection) DriverManager.getConnection(URL, USERNAME, PASSWORD);
      System.out.println("链接数据库成功");
    } catch (Exception e) {
      System.out.println("链接数据库失败");
    }
  }

  /**
   * 获取连接
   *
   * @return
   */
  public static Connection getConn() {
    if (conn == null) {
      conn = new DbUtils().getConn();
    }
    return conn;
  }

  public static ResultSet query(String sql, Object... param) {
    if (conn == null) {
      conn = new DbUtils().getConn();
    }
    ResultSet resultSet = null;
    if (param != null) {
      try {
        PreparedStatement ps = conn.prepareStatement(sql);//获取sql语句
        for (int i = 0; i < param.length; i++) {
          if (param[i] instanceof String) {
            ps.setString(i + 1, (String) param[i]);
          } else if (param[i] instanceof Integer) {
            ps.setInt(i + 1, (Integer) param[i]);
          } else if (param[i] instanceof Boolean) {
            ps.setBoolean(i + 1, (Boolean) param[i]);
          }
        }
        return ps.executeQuery();
      } catch (SQLException e) {
        e.printStackTrace();
      }
    }
    return resultSet;
  }

  public static boolean update(String sql, Object... param) {
    if (conn == null) {
      conn = new DbUtils().getConn();
    }
    boolean res = false;
    try {
      PreparedStatement ps = conn.prepareStatement(sql);//获取sql语句
      for (int i = 0; i < param.length; i++) {
        if (param[i] instanceof String) {
          ps.setString(i + 1, (String) param[i]);
        } else if (param[i] instanceof Integer) {
          ps.setInt(i + 1, (Integer) param[i]);
        } else if (param[i] instanceof Date) {
          ps.setString(i + 1, new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(param[i]));
        }
      }
      res = ps.execute();
    } catch (SQLException e) {
      e.printStackTrace();
    }
    return res;
  }

}
